﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Skyworth.CRM.Common;
using Skyworth.CRM.Service.IBLL;
using Skyworth.CRM.Service.Entity;

namespace Skyworth.CRM.Web.SystemManagement
{
    public partial class EditUser : BasePage
    {
        private IRoleBLL roleBll = (IRoleBLL)IocContainer.Instance.Resolve<IRoleBLL>();
        private IUserBLL userBll = (IUserBLL)IocContainer.Instance.Resolve<IUserBLL>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    BinDropDownList<CheckBoxList>(this.chklRole, roleBll.Query("",null), "", "");
                    if ("update" == Request.QueryString["Type"].ToString().ToLower())
                    {
                        int userId = 0;
                        int.TryParse(Request.QueryString["UserId"], out userId);
                        DataTable dtUser = userBll.Query(" and tsu.UserID=" + userId);
                        if (dtUser.Rows.Count > 0)
                        {
                            DataRow dr = dtUser.Rows[0];
                            this.txtUserName.Text = dr["UserName"].ToString();
                            //this.txtPassword.Text = dr["Password"].ToString();
                            this.txtPassword.Attributes.Add("value", dr["Password"].ToString());
                            ViewState["Password"] = dr["Password"].ToString();
                            BinDropDownList<DropDownList>(this.ddlstUserType, dr["UserType"].ToString(), true);
                            BinDropDownList<CheckBoxList>(this.chklRole, dr["roleid"].ToString().Trim(), true);
                            this.txtEmail.Text = dr["Email"].ToString();
                            this.hitIndividualId.Value = dr["IndividualId"].ToString();
                            if (dr["UserType"].ToString() == "1")// 员工
                            {
                                this.txtEmpId.Value = dr["NewName"].ToString();
                                //this.txtCustId.Visible = false;
                            }
                            else //客户
                            {
                                this.txtCustId.Value = dr["NewName"].ToString();
                                //this.txtEmpId.Visible = false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {                    
                     Logger.Instance.Error(ex);
                     Alert("发生异常：\r\n" + ex.Message);
                }                
            }
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                Users model = new Users();
                model.UserName = txtUserName.Text.Trim();
                model.UserType = Convert.ToInt32(ddlstUserType.SelectedValue);
                model.IndividualId = Convert.ToInt32(this.hitIndividualId.Value);
                model.Email = this.txtEmail.Text.Trim();
                List<int> roles = new List<int>();
                foreach (ListItem itms in this.chklRole.Items)
                {
                    if (itms.Selected)
                        roles.Add(Convert.ToInt32(itms.Value));
                }
                int uId = 0;
                int individual = 0;
                int userType = 1;
                bool temp = userBll.Exists(model.UserName, "", out uId, out individual, out userType);
                if ("add" == Request.QueryString["Type"].ToString().ToLower())
                {
                    model.Password = Encrypt.MD5(this.txtPassword.Text.Trim(), 32);
                    if (!temp)
                    {
                        userBll.Add(model, roles);
                        //Alert("新增成功!");
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "closeThisPage", "<script language=\"JavaScript\">parent.addWindow.close();parent.location.href = parent.location.href; alert('新增成功！')</script>");
                    }
                    else
                        Alert("对不起,此用户名己存在,请重新输入!");
                }
                else if ("update" == Request.QueryString["Type"].ToString().ToLower())
                {
                    model.Password = ViewState["Password"].ToString() != this.txtPassword.Text.Trim() ? Encrypt.MD5(this.txtPassword.Text.Trim(), 32) : this.txtPassword.Text.Trim();
                    int userId = 0;
                    int.TryParse(Request.QueryString["UserId"], out userId);
                    if (temp == false || (temp == true && uId == userId))
                    {
                        model.UserId = userId;
                        userBll.Update(model, roles);
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "closeThisPage", "<script language=\"JavaScript\">parent.addWindow.close();parent.location.href = parent.location.href; alert('修改成功')</script>");
                    }
                    else
                        Alert("对不起,此用户名己存在,请重新输入!");
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Error(ex);
                Alert("发生异常：\r\n" + ex.Message);
            }            
        }
    }
}